package com.newland.mesdk.demo.fragment;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.DeviceInvokeException;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.pin.AccountInputType;
import com.newland.mtype.module.common.pin.EncryptType;
import com.newland.mtype.module.common.pin.K21PininutEvent;
import com.newland.mtype.module.common.pin.KekUsingType;
import com.newland.mtype.module.common.pin.KeyManageType;
import com.newland.mtype.module.common.pin.MacAlgorithm;
import com.newland.mtype.module.common.pin.PinConfirmType;
import com.newland.mtype.module.common.pin.PinInputEvent;
import com.newland.mtype.module.common.pin.WorkingKey;
import com.newland.mtype.module.common.pin.WorkingKeyType;
import com.newland.mtype.module.common.swiper.SwipResult;
import com.newland.mtype.util.Dump;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.activity.N900KeyBoardNumberActivity;
import com.newland.mesdk.demo.event.RadioGroupChangeListener;
import com.newland.mesdk.demo.interfaceimpl.K21PininputInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.PinInputInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 密码输入模块
 */
public class PinFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private TextView tvOperationMessage;
	private StringBuffer stringBuffer;
	private PinInputInterfaceImpl pinInputInterfaceImpl;
	private String connectType, deviceType;
	private EncryptType encryptType = EncryptType.ENCRYPT_CBC;
	private String workingkey;
	private int inputLen = 0;
	private RadioGroup radioGroup_wk_index, radioGroup_encrypt_type1;
	private RadioButton radio_CBC, radio_ECB;
	private int temp_param_index = Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX;
	private EditText edit_encryption_value;
	private byte[] result, decryresult;
	protected static final String MAINKEY = "253C9D9D7C2FBBFA253C9D9D7C2FBBFA";// 预设输入值
	protected static final String WORKINGKEY_DATA_MAC = "DBFE96D0A5F09D24";// 预设输入值
	protected static final String WORKINGKEY_DATA_TRACK = "DBFE96D0A5F09D24DBFE96D0A5F09D24";// 预设输入值
	protected static final String WORKINGKEY_DATA_PIN = "D2CEEE5C1D3AFBAF00374E0CC1526C86";// 预设输入值
	private SwipResult swipRslt;
	private Button btnLoadMk, btnLoadWk, btnPinInput;
	private Button btnCanclePininput, btnCalMac, btnEncry, btnDecry;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_pin, null);
		mainActivity = (MainActivity) getActivity();
		tvOperationMessage = (TextView) mainActivity.findViewById(R.id.test_info);
		connectType = SharedPreferencesUtil.getStringParam(mainActivity, Const.CONNECTTYPE);
		deviceType = SharedPreferencesUtil.getStringParam(mainActivity, Const.DEVICETYPE);
		swipRslt = ((MyApplication) ((mainActivity).getApplication())).getSwipResult();

		initPinFragmentView(view);

		return view;
	}

	public void initPinFragmentView(View view) {
		btnLoadMk = (Button) view.findViewById(R.id.btn_pin_load_mk);
		btnLoadMk.setOnClickListener(this);

		btnLoadWk = (Button) view.findViewById(R.id.btn_pin_load_wk);
		btnLoadWk.setOnClickListener(this);

		btnPinInput = (Button) view.findViewById(R.id.btn_pin_pininput);
		btnPinInput.setOnClickListener(this);

		btnCanclePininput = (Button) view.findViewById(R.id.btn_pin_canle_pininput);
		btnCanclePininput.setOnClickListener(this);

		btnCalMac = (Button) view.findViewById(R.id.btn_pin_cal_mac);
		btnCalMac.setOnClickListener(this);

		btnEncry = (Button) view.findViewById(R.id.btn_pin_encry);
		btnEncry.setOnClickListener(this);

		btnDecry = (Button) view.findViewById(R.id.btn_pin_decry);
		btnDecry.setOnClickListener(this);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2: // 键盘输入
				int len = (Integer) msg.obj;
				stringBuffer = new StringBuffer();
				for (int i = 0; i < len; i++) {
					stringBuffer.append(" * ");
				}
				tvOperationMessage.setText("正在密码输入:" + stringBuffer.toString());
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			mainActivity.connectDevice();
			pinInputInterfaceImpl = new PinInputInterfaceImpl();
			switch (v.getId()) {
			case R.id.btn_pin_load_mk:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								byte[] mainKey = pinInputInterfaceImpl.loadMainKey(KekUsingType.ENCRYPT_TMK,
										Const.MKIndexConst.DEFAULT_MK_INDEX, ISOUtils.hex2byte(MAINKEY),
										ISOUtils.hex2byte("82E13665"), 1);
								if (mainKey == null) {
									mainActivity.showMessage("主密钥装载失败!" + "\r\n", MessageTag.TIP);
									mainActivity.processingUnLock();
								} else {
									mainActivity.showMessage("主密钥装载成功!" + "\r\n", MessageTag.TIP);
									mainActivity.showMessage("主密钥装载返回的数据：" + ISOUtils.hexString(mainKey) + "\r\n",
											MessageTag.DATA);
									mainActivity.processingUnLock();
								}

							} catch (Exception e) {
								mainActivity.showMessage("主密钥装载失败" + e.getMessage() + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();
				}

				break;
			case R.id.btn_pin_load_wk:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showLoadWorkingKeyDiaolg(mainActivity);

						}
					}).start();

				}

				break;
			case R.id.btn_pin_pininput:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							if (null == swipRslt) {
								mainActivity.showMessage("请先到刷卡模块刷卡再输入密码!" + "\r\n", MessageTag.TIP);
								mainActivity.processingUnLock();
							} else {
								// IM81输密码
								mainActivity.showMessage("请输入6位密码:" + "\r\n", MessageTag.TIP);
								if (connectType.equals(Const.ConnectTypeName.K21)
										&& deviceType.equals(Const.DeviceName.IM81)) {
									try {
										K21PininputInterfaceImpl k21PinputInterfaceImpl = new K21PininputInterfaceImpl();
										k21PinputInterfaceImpl.startK21StandPininput("IM81开始输入密码", new WorkingKey(
												Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX), KeyManageType.MKSK,
												AccountInputType.USE_ACCT_HASH, swipRslt.getAccount().getAcctHashId(),
												6, null,
												new byte[] { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' },
												PinConfirmType.ENABLE_ENTER_COMMANG, 60, TimeUnit.SECONDS, null, null,
												new DeviceEventListener<K21PininutEvent>() {
													@Override
													public void onEvent(K21PininutEvent event, Handler handler) {
														if (event == null) {
															inputLen = 0;
															mainActivity.showMessage("密码输入撤销", MessageTag.TIP);
															mainActivity.processingUnLock();
														} else if (event.isSuccess()) {
															inputLen = 0;
															mainActivity.showMessage("密码输入完成", MessageTag.TIP);
															mainActivity.showMessage(
																	"ksn:" + Dump.getHexDump(event.getKsn()),
																	MessageTag.DATA);
															mainActivity.showMessage(
																	"密码:" + Dump.getHexDump(event.getEncrypPin()),
																	MessageTag.DATA);
															mainActivity.processingUnLock();
														} else if (event.isProcessing()) {
															PinInputEvent.NotifyStep notifyStep = event.getNotifyStep();
															if (notifyStep == PinInputEvent.NotifyStep.ENTER) {
																inputLen = inputLen + 1;
															} else if (notifyStep == PinInputEvent.NotifyStep.BACKSPACE) {
																inputLen = (inputLen <= 0 ? 0 : inputLen - 1);
																mainActivity.showMessage("按了退格键:" + inputLen,
																		MessageTag.TIP);
															}
															Message msg = mHandler.obtainMessage(2);
															msg.obj = inputLen;
															msg.sendToTarget();
														} else if (event.isUserCanceled()) {
															inputLen = 0;
															mainActivity.showMessage("用户撤销密码输入", MessageTag.TIP);
															mainActivity.processingUnLock();
														}
													}

													@Override
													public Handler getUIHandler() {
														return null;
													}
												});
									} catch (Exception e) {
										mainActivity.showMessage("IM81密码输入异常：" + e + "\r\n", MessageTag.ERROR);
										mainActivity.processingUnLock();
									}

									// N900输密码
								} else if (connectType.equals(Const.ConnectTypeName.K21)
										&& deviceType.equals(Const.DeviceName.N900)) {
									try {
										mainActivity.processingLock();
										Message msg = MainActivity.getPinHandler().obtainMessage(1);
										msg.sendToTarget();
									} catch (Exception e) {
										mainActivity.showMessage("N900密码输入异常：" + e + "\r\n", MessageTag.ERROR);
										mainActivity.processingUnLock();
									}

								} else if (deviceType.equals(Const.DeviceName.ME30)
										|| deviceType.equals(Const.DeviceName.ME31)) {
									try {
										PinInputEvent event = pinInputInterfaceImpl.startStandardPinInput(
												new WorkingKey(Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX),
												KeyManageType.MKSK, AccountInputType.USE_ACCT_HASH, swipRslt
														.getAccount().getAcctHashId(), 6, new byte[] { 'F', 'F', 'F',
														'F', 'F', 'F', 'F', 'F', 'F', 'F' }, true, "请输入密码", 30,
												TimeUnit.SECONDS);
										if (event == null) {
											mainActivity.showMessage("密码输入撤销" + "\r\n", MessageTag.TIP);
											mainActivity.processingUnLock();
										} else if (event.isSuccess()) {
											mainActivity.showMessage("密码输入完成" + "\r\n", MessageTag.TIP);
											mainActivity.showMessage("ksn:" + Dump.getHexDump(event.getKsn()) + "\r\n",
													MessageTag.DATA);
											mainActivity.showMessage("密码:" + Dump.getHexDump(event.getEncrypPin())
													+ "\r\n", MessageTag.DATA);
											mainActivity.processingUnLock();
										} else if (event.isUserCanceled()) {
											mainActivity.showMessage("撤销密码输入" + "\r\n", MessageTag.TIP);
											mainActivity.processingUnLock();
										}
									} catch (Exception e) {
										mainActivity.showMessage("密码输入异常：" + e + "\r\n", MessageTag.ERROR);
										mainActivity.processingUnLock();
									}
								}
							}

						}
					}).start();

				}

				break;
			case R.id.btn_pin_canle_pininput:
				new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							mainActivity.processingUnLock();
							mainActivity.getController().reset();
							mainActivity.showMessage("撤消上一次的密码输入成功！" + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("撤消上一次的密码输入成功 异常！" + e + "\r\n", MessageTag.ERROR);
							mainActivity.processingUnLock();
						}

					}
				}).start();

				break;
			case R.id.btn_pin_cal_mac:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showCalMacDialog(mainActivity);

						}
					}).start();

				}

				break;
			case R.id.btn_pin_encry:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showEncryptDiolog(mainActivity);

						}
					}).start();
				}

				break;
			case R.id.btn_pin_decry:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showDecryptDialog(mainActivity);

						}
					}).start();

				}

				break;

			default:
				break;
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.TIP);
		}
	}

	// 计算MAC对话框
	public void showCalMacDialog(final Activity activity) {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final EditText edit_caclmac_value;
				final RadioGroupChangeListener radioGroupChangeListener;
				final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				LayoutInflater inflater = LayoutInflater.from(activity);
				final View view = inflater.inflate(R.layout.dialog_caclmac, null);
				builder.setView(view);
				edit_caclmac_value = (EditText) view.findViewById(R.id.edit_caclmac_value);
				edit_caclmac_value.setHint("test data");
				radioGroupChangeListener = new RadioGroupChangeListener(view, Const.DialogView.MAC_CACL_DIALOG);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							String string = edit_caclmac_value.getText().toString();
							byte[] input = string.getBytes("GBK");
							MacAlgorithm macAlgorithm = radioGroupChangeListener.getMacAlgorithm();
							byte[] ouput = pinInputInterfaceImpl.calcMac(macAlgorithm, KeyManageType.MKSK,
									new WorkingKey(Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX), input).getMac();
							mainActivity.showMessage("输入值:" + string + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("计算方式:" + macAlgorithm + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("MAC计算结果:" + Dump.getHexDump(ouput) + "\r\n", MessageTag.DATA);

							mainActivity.processingUnLock();
						} catch (DeviceInvokeException e) {
							mainActivity.showMessage("输入值不能为空" + e.getMessage() + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} catch (UnsupportedEncodingException e) {
							mainActivity.showMessage("输入数值有误" + "\r\n", MessageTag.ERROR);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage(e.getMessage(), MessageTag.ERROR);
							mainActivity.processingUnLock();
						}
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						mainActivity.processingUnLock();
					}
				});
				Dialog dialog_caclmac = builder.create();
				dialog_caclmac.setTitle("计算MAC:");
				dialog_caclmac.show();
				dialog_caclmac.setCancelable(false);
				dialog_caclmac.setCanceledOnTouchOutside(false);
			}
		});
	}

	// 解密对话框
	public void showDecryptDialog(final Activity activity) {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				LayoutInflater inflater = LayoutInflater.from(activity);
				final View view = inflater.inflate(R.layout.dialog_encryption, null);
				radioGroup_encrypt_type1 = (RadioGroup) view.findViewById(R.id.radioGroup_encrypt_type1);
				radio_CBC = (RadioButton) view.findViewById(R.id.radio_CBC);
				radio_ECB = (RadioButton) view.findViewById(R.id.radio_ECB);
				radioGroup_wk_index = (RadioGroup) view.findViewById(R.id.radioGroup_wk_index);
				temp_param_index = Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX;
				workingkey = "MAC";
				radioGroup_wk_index.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup arg0, int arg1) {
						if (arg1 == R.id.radio_mac) {
							temp_param_index = Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX;
							workingkey = "MAC";
						} else if (arg1 == R.id.radio_track) {
							temp_param_index = Const.DataEncryptWKIndexConst.DEFAULT_TRACK_WK_INDEX;
							workingkey = "TRACK";
						}

					}
				});
				edit_encryption_value = (EditText) view.findViewById(R.id.edit_encryption_value);
				if (((MyApplication) activity.getApplication()).getResult() == null) {
					edit_encryption_value.setHint("请先加密或输入测试数据");
				} else {
					edit_encryption_value.setText(ISOUtils.hexString(((MyApplication) activity.getApplication())
							.getResult()));
				}
				TextView text_encrypt = (TextView) view.findViewById(R.id.text_encrypt);
				text_encrypt.setText("待解密数据：");
				encryptType = EncryptType.DECRYPT_CBC;
				radioGroup_encrypt_type1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup arg0, int arg1) {
						if (arg1 == radio_CBC.getId()) {
							encryptType = EncryptType.DECRYPT_CBC;
						} else if (arg1 == radio_ECB.getId()) {
							encryptType = EncryptType.DECRYPT_ECB;
						}

					}
				});

				builder.setView(view);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							byte[] input = ISOUtils.hex2byte(edit_encryption_value.getText().toString());
							decryresult = pinInputInterfaceImpl.decrypt(new WorkingKey(temp_param_index), encryptType,
									input, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
							mainActivity.showMessage("解密数据:" + edit_encryption_value.getText().toString() + "\r\n",
									MessageTag.DATA);
							mainActivity.showMessage("解密密钥:" + workingkey + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("解密模式:" + encryptType + "\r\n", MessageTag.DATA);
							mainActivity
									.showMessage("解密结果:" + Dump.getHexDump(decryresult) + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("提示:若于加密前数据不一致，请检查解密密钥与模式是否与加密保持一致" + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("解密异常" + e.getMessage() + "\r\n", MessageTag.ERROR);
							mainActivity.processingUnLock();
						} 
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						mainActivity.processingUnLock();
					}
				});
				Dialog encrypt_dialog = builder.create();
				encrypt_dialog.setTitle("解密");
				encrypt_dialog.show();
				encrypt_dialog.setCancelable(false);
				encrypt_dialog.setCanceledOnTouchOutside(false);
			}
		});
	}

	// 加密对话框
	public void showEncryptDiolog(final Activity activity) {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				LayoutInflater inflater = LayoutInflater.from(activity);
				final View view = inflater.inflate(R.layout.dialog_encryption, null);
				radioGroup_encrypt_type1 = (RadioGroup) view.findViewById(R.id.radioGroup_encrypt_type1);
				radio_CBC = (RadioButton) view.findViewById(R.id.radio_CBC);
				radio_ECB = (RadioButton) view.findViewById(R.id.radio_ECB);
				radioGroup_wk_index = (RadioGroup) view.findViewById(R.id.radioGroup_wk_index);
				temp_param_index = Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX;
				workingkey = "MAC";
				radioGroup_wk_index.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup arg0, int arg1) {
						if (arg1 == R.id.radio_mac) {
							temp_param_index = Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX;
							workingkey = "MAC";
						} else if (arg1 == R.id.radio_track) {
							temp_param_index = Const.DataEncryptWKIndexConst.DEFAULT_TRACK_WK_INDEX;
							workingkey = "TRACK";
						}

					}
				});
				edit_encryption_value = (EditText) view.findViewById(R.id.edit_encryption_value);
				edit_encryption_value.setText("BF20150904");
				TextView text_encrypt = (TextView) view.findViewById(R.id.text_encrypt);
				text_encrypt.setText("待加密数据：");
				encryptType = EncryptType.ENCRYPT_CBC;
				radioGroup_encrypt_type1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup arg0, int arg1) {
						if (arg1 == radio_CBC.getId()) {
							encryptType = EncryptType.ENCRYPT_CBC;
						} else if (arg1 == radio_ECB.getId()) {
							encryptType = EncryptType.ENCRYPT_ECB;
						}
					}
				});
				builder.setView(view);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							byte[] input = edit_encryption_value.getText().toString().getBytes("GBK");
							result = pinInputInterfaceImpl.encrypt(new WorkingKey(temp_param_index), encryptType,
									input, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 });
							mainActivity.showMessage("加密成功!" + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("加密数据:" + edit_encryption_value.getText().toString() + "\r\n",
									MessageTag.DATA);
							mainActivity.showMessage("加密密钥:" + workingkey + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("加密模式:" + encryptType + "\r\n", MessageTag.DATA);
							mainActivity.showMessage("加密结果:" + ISOUtils.hexString(result) + "\r\n", MessageTag.DATA);
							((MyApplication) activity.getApplication()).setResult(result);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("加密异常" + e.getMessage() + "\r\n", MessageTag.ERROR);
							mainActivity.processingUnLock();
						}
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						mainActivity.processingUnLock();
					}
				});
				Dialog encrypt_dialog = builder.create();
				encrypt_dialog.setTitle("加密");
				encrypt_dialog.show();
				encrypt_dialog.setCancelable(false);
				encrypt_dialog.setCanceledOnTouchOutside(false);
			}
		});
	}

	// 装载工作秘钥对话框
	public void showLoadWorkingKeyDiaolg(final Activity activity) {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					final boolean[] arrayWorkingKeySelected = new boolean[] { false, false, false };
					final String[] arrayWorkingKey = new String[] { "PIN密钥", "磁道密钥", "MAC密钥" };
					final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(activity);
					builder.setTitle("请选择需装载工作密钥类型:");
					builder.setMultiChoiceItems(arrayWorkingKey, arrayWorkingKeySelected,
							new DialogInterface.OnMultiChoiceClickListener() {
								@Override
								public void onClick(DialogInterface arg0, int arg1, boolean arg2) {
									arrayWorkingKeySelected[arg1] = arg2;
								}
							});
					builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							try {
								mainActivity.showMessage("正在装载工作密钥..." + "\r\n", MessageTag.TIP);
								int mkIndex = Const.MKIndexConst.DEFAULT_MK_INDEX;
								if (arrayWorkingKeySelected[0] == true) {
									byte[] wk_pin = pinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.PININPUT,
											mkIndex, Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_PIN), ISOUtils.hex2byte("58A2BBF9"));
									if (wk_pin != null) {
										mainActivity.showMessage("pin工作密钥装载成功!" + "\r\n", MessageTag.DATA);
									} else {
										mainActivity.showMessage("pin工作密钥装载失败!" + "\r\n", MessageTag.ERROR);
									}
								}
								if (arrayWorkingKeySelected[1] == true) {
									byte[] wk_encrypt = pinInputInterfaceImpl.loadWorkingKey(
											WorkingKeyType.DATAENCRYPT, mkIndex,
											Const.DataEncryptWKIndexConst.DEFAULT_TRACK_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_TRACK), ISOUtils.hex2byte("5B4C8BED"));
									if (wk_encrypt != null) {
										mainActivity.showMessage("磁道工作密钥装载成功!" + "\r\n", MessageTag.DATA);
									} else {
										mainActivity.showMessage("磁道工作密钥装载失败!" + "\r\n", MessageTag.ERROR);
									}
								}
								if (arrayWorkingKeySelected[2] == true) {
									byte[] wk_mac = pinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.MAC, mkIndex,
											Const.MacWKIndexConst.DEFAULT_MAC_WK_INDEX,
											ISOUtils.hex2byte(WORKINGKEY_DATA_MAC), ISOUtils.hex2byte("5B4C8BED"));
									if (wk_mac != null) {
										mainActivity.showMessage("mac工作密钥装载成功!" + "\r\n", MessageTag.DATA);
									} else {
										mainActivity.showMessage("mac工作密钥装载失败!" + "\r\n", MessageTag.ERROR);
									}
								}
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage(e.getMessage() + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							mainActivity.processingUnLock();
						}
					});
					Dialog workingkey_dialog = builder.create();
					workingkey_dialog.setCancelable(false);
					workingkey_dialog.setCanceledOnTouchOutside(false);
					workingkey_dialog.show();
				} catch (Exception ex) {
					mainActivity.showMessage("工作密钥装载失败!" + ex.getMessage() + "\r\n", MessageTag.ERROR);
					mainActivity.processingUnLock();
				}
			}
		});
	}

}
